package com.csi.dao.impl;

import com.csi.dao.GuestsDao;
import com.csi.domain.Guests;
import com.csi.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class GuestsDaoImpl extends JDBCUtils implements GuestsDao {
    @Override
    public List<Guests> findAll() throws SQLException {
        final  String sql="select*from hotel_guests";

        Connection connection = this.getConnection();

        PreparedStatement ps = connection.prepareStatement(sql);

        ResultSet rs = ps.executeQuery();

        List<Guests> list=new ArrayList<>();

        while (rs.next()){
            Guests guests=new Guests();

            guests.setGuestsId(rs.getInt("guestsId"));

            guests.setGuestsCard(rs.getString("guestsCard"));

            guests.setGuestsName(rs.getString("guestsName"));

            guests.setGuestsSex(rs.getString("guestsSex"));

            guests.setGuestsPhone(rs.getString("guestsPhone"));

            list.add(guests);

        }

        this.release(rs,ps,connection);

        return list;
    }

    @Override
    public int insert(Guests guests) throws SQLException {
        final String sql="insert into hotel_guests(guestsName,guestsCard,guestsSex,guestsPhone)values(?,?,?,?)";
        Connection connection = this.getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,guests.getGuestsName());
        ps.setString(2,guests.getGuestsCard());
        ps.setString(3,guests.getGuestsSex());
        ps.setString(4,guests.getGuestsPhone());

        int i = ps.executeUpdate();

        this.release(ps,connection);

        return i;
    }

    @Override
    public int update(Guests guests) throws SQLException {

        final  String sql="update hotel_guests set guestsName=?,guestsCard=?,guestsSex=?,guestsPhone=? where guestsId=?";

        Connection connection = this.getConnection();

        PreparedStatement ps = connection.prepareStatement(sql);

        ps.setString(1,guests.getGuestsName());
        ps.setString(2,guests.getGuestsCard());
        ps.setString(3,guests.getGuestsSex());
        ps.setString(4,guests.getGuestsPhone());
        ps.setInt(5,guests.getGuestsId());

        int i = ps.executeUpdate();

        this.release(ps,connection);

        return i;
    }

    @Override
    public int delete(int guestsId) throws SQLException {

        final String sql="delete from hotel_guests where guestsId=?";

        Connection connection = this.getConnection();

        PreparedStatement ps = connection.prepareStatement(sql);

        ps.setInt(1,guestsId);

        int i = ps.executeUpdate();

        this.release(ps,connection);

        return i;
    }
}
